package com.derbysoft.lowcostadapter.commons.redis.service.impl;

import com.derbysoft.lowcostadapter.commons.model.AvailabilityProvider;
import com.derbysoft.lowcostadapter.commons.model.Channel;
import com.derbysoft.lowcostadapter.commons.redis.service.ChannelCacheService;
import com.derbysoft.lowcostadapter.commons.redis.utils.KeyValueHelper;
import com.derbysoft.redis.clients.normal.SingleJedis;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * User: jason
 * Date: 2012-11-15
 */
@Repository("channelCacheService")
public class ChannelCacheServiceImpl implements ChannelCacheService {

    @Autowired
    private SingleJedis systemConfigRedis;

    @Override
    public Channel get(String channelCode) {
        return getByKey(Channel.PREFIX + StringUtils.upperCase(channelCode));
    }

    @Override
    public List<Channel> loadAll() {
        List<Channel> channels = new ArrayList<Channel>();
        for (String key : systemConfigRedis.keys(Channel.PREFIX + "*")) {
            Channel channel = getByKey(key);
            if (channel != null) {
                channels.add(channel);
            }
        }
        return channels;
    }

    @Override
    public void saveAll(List<Channel> channels) {
        for (Channel channel : channels) {
            systemConfigRedis.set(channel.toKey(), channel.toValue());
        }
    }

    private Channel getByKey(String key) {
        String value = systemConfigRedis.get(key);
        if (StringUtils.isBlank(value)) {
            return null;
        }
        String[] fields = StringUtils.split(value, KeyValueHelper.SEPARATOR);
        AvailabilityProvider availabilityProvider = AvailabilityProvider.from(fields[1]);
        if (availabilityProvider == null) {
            return null;
        }
        Channel channel = new Channel();
        channel.setChannelCode(StringUtils.split(key, KeyValueHelper.SEPARATOR)[1]);
        channel.setChannelName(fields[0]);
        channel.setAvailabilityProvider(availabilityProvider);
        channel.setNormalMakeReservation(Boolean.parseBoolean(fields[2]));
        return channel;
    }
}
